<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
            <el-form-item label="线索名称" prop="name">
                <el-input
                        v-model="queryParams.name"
                        placeholder="请输入客户名称"
                        clearable
                        style="width: 200px"
                        @keyup.enter="handleQuery"
                />
            </el-form-item>
            <el-form-item label="线索归属" prop="owner">
                <el-input
                    v-model="queryParams.owner"
                    placeholder="线索归属"
                    clearable
                    style="width: 200px"
                    @keyup.enter="handleQuery"
                />
            </el-form-item>
            <el-form-item label="客户手机号码" prop="phone">
                <el-input
                    v-model="queryParams.phone"
                    placeholder="请输入客户手机号码"
                    clearable
                    style="width: 200px"
                    @keyup.enter="handleQuery"
                />
            </el-form-item>
            <el-form-item label="渠道来源" prop="channelId">
                <el-select
                    v-model="queryParams.channelId"
                    placeholder="渠道来源"
                    clearable
                    style="width: 240px"
                    @keyup.enter="handleQuery"
                >
                    <el-option
                        v-for="cl in channelList"
                        :key="cl.channelId"
                        :label="cl.channelName"
                        :value="cl.channelId"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="线索状态" prop="status">
                <el-select
                    v-model="queryParams.status"
                    placeholder="线索状态"
                    clearable
                    style="width: 240px"
                    @keyup.enter="handleQuery"
                >
                    <el-option
                        v-for="cs in clue_status"
                        :key="cs.value"
                        :label="cs.label"
                        :value="cs.value"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="跟进时间">
                <el-date-picker
                    v-model="dateRange"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    format="YYYY-MM-DD HH:mm:ss"
                    type="datetimerange"
                    range-separator="-"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                ></el-date-picker>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                        type="primary"
                        plain
                        icon="Plus"
                        @click="handleAdd"
                        v-hasPermi="['tienchin:clue:create']"
                >新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="success"
                        plain
                        icon="Edit"
                        :disabled="single"
                        @click="handleUpdate"
                        v-hasPermi="['tienchin:clue:edit']"
                >修改</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="danger"
                        plain
                        icon="Delete"
                        :disabled="multiple"
                        @click="handleDelete"
                        v-hasPermi="['tienchin:clue:remove']"
                >删除</el-button>
            </el-col>
<!--            <el-col :span="1.5">
                <el-button
                        type="warning"
                        plain
                        icon="Download"
                        @click="handleExport"
                        v-hasPermi="['tienchin:clue:export']"
                >导出</el-button>
            </el-col>-->
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="clueList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column label="线索编号" align="center" prop="clueId" width="80"/>
            <el-table-column label="客户姓名" align="center" prop="name" width="120"/>
            <el-table-column label="电话号码" align="center" prop="phone" width="120"/>
            <el-table-column label="渠道来源" align="center" prop="channelName" width="120"/>
            <el-table-column label="创建时间" align="center" prop="createTime" width="180">
                <template #default="scope">
                    <span>{{ parseTime(scope.row.createTime) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="线索状态" align="center" width="120">
                <template #default="scope">
                    <dict-tag :options="clue_status" :value="scope.row.status" />
                </template>
            </el-table-column>
            <el-table-column label="线索归属" align="center" prop="owner" width="120"/>
            <el-table-column label="下次跟进时间" align="center" prop="createTime" width="180">
                <template #default="scope">
                    <span>{{ parseTime(scope.row.nextTime) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button link type="primary" icon="View" @click="handleClueView(scope.row)" v-hasPermi="['tienchin:clue:view']">查看</el-button>
                    <el-button link v-if="scope.row.status==1" type="primary" icon="Pointer" @click="handleAssign(scope.row)" v-hasPermi="['tienchin:clue:assign']">分配</el-button>
                    <el-button link v-if="scope.row.owner==userStore.name &&(scope.row.status==1||scope.row.status==2)" type="primary" icon="TopRight" @click="handleClueFollow(scope.row)" v-hasPermi="['tienchin:clue:follow']">跟进</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination
                v-show="total > 0"
                :total="total"
                v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize"
                @pagination="getList"
        />

        <!-- 添加或修改线索对话框 -->
        <el-dialog :title="title" v-model="open" width="700px" append-to-body>
            <el-form ref="clueRef" :model="form" :rules="rules" label-width="80px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="客户姓名" prop="name">
                            <el-input v-model="form.name" placeholder="请输入客户姓名" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="联系方式" prop="phone">
                            <el-input v-model="form.phone" placeholder="请输入手机号码" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="渠道来源" prop="channelId">
                            <el-select
                                    v-model="form.channelId"
                                    placeholder="渠道来源"
                                    @change="channelChange"
                                    clearable
                                    style="width: 240px"
                            >
                                <el-option
                                        v-for="cl in channelList"
                                        :key="cl.channelId"
                                        :label="cl.channelName"
                                        :value="cl.channelId"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="活动信息" prop="activityId">
                            <el-select
                                    v-model="form.activityId"
                                    placeholder="活动信息"
                                    clearable
                                    style="width: 240px"
                            >
                                <el-option
                                        v-for="ac in activityList"
                                        :key="ac.activityId"
                                        :label="ac.activityName"
                                        :value="ac.activityId"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="客户性别" prop="gender">
                            <el-radio-group v-model="form.gender">
                                <el-radio
                                        v-for="dict in sys_user_sex"
                                        :key="dict.value"
                                        :label="parseInt(dict.value)"
                                >{{ dict.label }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="客户年龄" prop="age">
                            <el-input-number v-model="form.age" :min="6" :max="100" placeholder="年龄"/>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="微信" prop="weixin">
                            <el-input v-model="form.weixin" placeholder="请输入微信" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="QQ" prop="qq">
                            <el-input v-model="form.qq" placeholder="请输入QQ" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
        <!-- 分配线索对话框 -->
        <el-dialog title="分配线索" v-model="assignClueDialog" width="700px" append-to-body>
            <el-form ref="clueAssignRef" :model="assignForm" :rules="assignFormRules" label-width="80px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="归属部门" prop="departmentId">
                            <el-tree-select
                                v-model="assignForm.departmentId"
                                :data="deptOptions"
                                :props="{ value: 'id', label: 'label', children: 'children' }"
                                value-key="id"
                                @change="deptChange"
                                placeholder="请选择归属部门"
                                check-strictly
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="分配给" prop="nickName">
                            <el-select
                                v-model="assignForm.nickName"
                                value-key="id"
                                placeholder="请选择用户"
                                @change="assignChange"
                                style="width: 240px"
                            >
                                <el-option
                                    v-for="ul in userList"
                                    :key="ul.userId"
                                    :label="ul.nickName"
                                    :value="{value:ul.userId,userName:ul.userName,nickName:ul.nickName,deptId:ul.deptId}"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="handleAssignClue">确 定</el-button>
                    <el-button @click="cancelAssignDialog">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="Clue">
import {
    listChannel,
    listActivityByChannelId,
    addClue,
    listClue,
    getUsersByDeptId,
    assignClue,
    updateClue,
    getClueSummaryById,
    delClue
} from "@/api/tienchin/clue";
import {deptTreeSelect} from "@/api/system/user";
import router from "@/router";
import useUserStore from "@/store/modules/user";

const userStore = useUserStore();
const { proxy } = getCurrentInstance();
const { sys_user_sex,clue_type,clue_status} = proxy.useDict("sys_user_sex","clue_type","clue_status");

const clueList = ref([]);
const channelList = ref([]);
const userList = ref([]);
const activityList = ref([]);
const open = ref(false);
const assignClueDialog = ref(false);
const deptOptions = ref(undefined);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);

const data = reactive({
    form: {},
    assignForm: {},
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        owner: undefined,
        phone: undefined,
        channelId: undefined,
        status: undefined,
    },
    rules: {
        phone: [{ required: true, message: "手机号码不能为空", trigger: "blur" }],
        name: [{ required: true, message: "客户名称不能为空", trigger: "blur" }],
    },
    assignFormRules:{
        departmentId: [{ required: true, message: "部门不能为空", trigger: "blur" }],
        nickName: [{ required: true, message: "分配用户不能为空", trigger: "blur" }],
    }
});

const { queryParams, form, rules,assignForm,assignFormRules} = toRefs(data);

/**
 * 获取所以渠道
 */
function getChannelList() {
    listChannel().then(response => {
        channelList.value = response.data;
    });
}
function channelChange(channelId){
    form.value.activityId = undefined;
    if (channelId != ''){
        listActivityByChannelId(channelId).then(response => {
            activityList.value = response.data;
        })
    }
}
/** 查询线索列表 */
function getList() {
    loading.value = true;
    listClue(proxy.addDateRange(queryParams.value, dateRange.value)).then(response => {
        clueList.value = response.rows;
        total.value = response.total;
        loading.value = false;
    });
}
//获取部门
function getDeptTree() {
    if (deptOptions.value === undefined){
        deptTreeSelect().then(response => {
            deptOptions.value = response.data;
        });
    }
}
//分配执行操作
function handleAssignClue(){
    proxy.$refs["clueAssignRef"].validate(valid => {
        if (valid) {
            assignClue(assignForm.value).then(response => {
                proxy.$modal.msgSuccess(response.msg);
                getList();
                assignClueDialog.value = false;
                resetAssignForm();
            })
        }
    });

}
//根据部门获取用户
function getUsers(){
    getUsersByDeptId(assignForm.value.departmentId).then(response => {
        userList.value = response.data;
    });
}
function assignChange(data){
    assignForm.value.nickName = data.nickName;
    assignForm.value.userId = data.value;
    assignForm.value.userName = data.userName;
    assignForm.value.deptId = data.deptId;
    //alert(JSON.stringify(data))
}
function deptChange(){
    assignForm.value.nickName = undefined;
    getUsers();
}
//重置线索分配表单
function resetAssignForm() {
    assignForm.value = {
        departmentId: undefined,
        nickName: undefined
    };
    proxy.resetForm("clueAssignRef");
}
function cancelAssignDialog() {
    assignClueDialog.value = false;
    resetAssignForm();
}

/** 取消按钮 */
function cancel() {
    open.value = false;
    reset();
}
/** 表单重置 */
function reset() {
    form.value = {
        name: undefined,
        phone: undefined,
        channelId: undefined,
        activityId: undefined,
        gender: undefined,
        weixin: undefined,
        qq: undefined,
        age: undefined
    };
    proxy.resetForm("clueRef");
}
/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
}
/** 重置按钮操作 */
function resetQuery() {
    dateRange.value = [];
    proxy.resetForm("queryRef");
    handleQuery();
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.clueId);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
}
/** 新增按钮操作 */
function handleAdd() {
    reset();
    getChannelList();
    open.value = true;
    title.value = "添加线索";
}
function handleUpdate(){
    reset();
    const clueId = ids.value;
    getChannelList();
    getClueSummaryById(clueId).then(response => {
        form.value = response.data;
        listActivityByChannelId(response.data.channelId).then(response => {
            activityList.value = response.data;
        })
        open.value = true;
        title.value = "修改线索";
    });

}
/** 跳转详情页面 */
function handleClueView(data) {
    //router.push("/system/user-auth/role/" + data.clueId);
    //router.push("/tienchin/clue/details")
    router.push("/clue/details/index/" + data.clueId + "/view")
}
function handleClueFollow(data){
    router.push("/clue/details/index/" + data.clueId+"/follow")
}
function handleAssign(data) {
    assignForm.value.assignId = data.clueId;
    //0表示线索
    assignForm.value.type = 0;
    getDeptTree();
    assignClueDialog.value = true;

}

/** 提交按钮 */
function submitForm() {
    proxy.$refs["clueRef"].validate(valid => {
        if (valid) {
            if (form.value.clueId != undefined) {
                updateClue(form.value).then(response => {
                    proxy.$modal.msgSuccess("修改成功");
                    open.value = false;
                    getList();
                });
            } else {
                addClue(form.value).then(response => {
                    proxy.$modal.msgSuccess("新增成功");
                    open.value = false;
                    getList();
                });
            }
        }
    });
}
/** 删除按钮操作 */
function handleDelete(row) {
    const clueIds = row.clueId || ids.value;
    proxy.$modal.confirm('是否确认删除岗位编号为"' + clueIds + '"的数据项？').then(function() {
        return delClue(clueIds);
    }).then(() => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
    }).catch(() => {});
}


getList();
getChannelList();
</script>
